package com.calvin.study.multithread.signal;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

//线程通知
public class ThreadWaitNotify {
	static Object objLock = new Object();

	static Lock lock = new ReentrantLock();
	static Condition condition = lock.newCondition();

	static AtomicInteger nums = new AtomicInteger(20);

	public static void main(String[] args) {
		 //synchronizedWaitNotify();
		//LockAwatiSignal();
		 LockSupportDemo();

	}

	private static void LockSupportDemo() {
		Thread a = new Thread(() -> {
			//ThreadSleep(1);
			System.out.println("当前线程：" + Thread.currentThread().getName() + "\t" + "------come in");
			LockSupport.park();// 阻塞当前线程 相当于wait和await
			System.out.println("当前线程：" + Thread.currentThread().getName() + "\t" + "------被唤醒");
		}, "A");
		
		a.start();

		new Thread(() -> {
			LockSupport.unpark(a);
			System.out.println("当前线程：" + Thread.currentThread().getName() + "\t" + "------通知");
		}, "B").start();
	}

	private static void LockAwatiSignal() {
		new Thread(() -> {
			lock.lock();
			try {
				System.out.println("当前线程：" + Thread.currentThread().getName() + "\t" + "------come in");
				try {
					ThreadSleep(1);
					condition.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("当前线程：" + Thread.currentThread().getName() + "\t" + "------被唤醒");
			} finally {
				lock.unlock();
			}
		}, "A").start();

		new Thread(() -> {
			lock.lock();
			try {
				System.out.println("当前线程：" + Thread.currentThread().getName() + "\t" + "------通知");
				condition.signal();
				ThreadSleep(1);
				System.out.println("当前线程：" + Thread.currentThread().getName() + "\t" + "------执行完成");
			} finally {
				lock.unlock();
			}
		}, "B").start();
	}

	private static void synchronizedWaitNotify() {
		new Thread(() -> {
			ThreadSleep(3);
			synchronized (objLock) {
				System.out.println("当前线程：" + Thread.currentThread().getName() + "\t" + "------come in");
				try {
					objLock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("当前线程：" + Thread.currentThread().getName() + "\t" + "------被唤醒");
			}
		}, "A").start();

		new Thread(() -> {
			synchronized (objLock) {
				objLock.notify();
				System.out.println("当前线程：" + Thread.currentThread().getName() + "\t" + "------通知");
			}
		}, "B").start();

	}

	public static void ThreadSleep(long timeout) {
		try {
			TimeUnit.SECONDS.sleep(timeout);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
	}
}
